import React,{useState,useEffect} from 'react'
import {
    Form,
    Input,
    Button,
    DatePicker,
    Space,
    Cascader
  } from 'antd';
  import Upload from '../../components/upload'
  import {post} from '@/Utils/axios'
  import { MinusCircleOutlined,PlusOutlined } from '@ant-design/icons';
  import {Url} from '@/Utils/services/url'
  import '../style/createIndex.less'
  import moment from "moment";
export default function Demo (props:any){
    const { RangePicker } = DatePicker;
    const [form] = Form.useForm()
    const [options, setOptions] = useState([])
    const [cityList,setCityList] = useState([])
    const [addressIsReady,setAddressIsReady] = useState(false)
    const url = Url.addressList
    function sumbit(){
      form.validateFields().then(res =>{
        let basicData = form.getFieldsValue(true)
        if(props.formData.id !== undefined){
          basicData = Object.assign({...props.formData},{...basicData})
        }
        const num = 2
        props.changeCreate(basicData,num)
      })
     
    }
    useEffect(()=>{
        searchFirstAddress()
    },[])
    useEffect(()=>{
      if(JSON.stringify(props.formData) !== '{}'){
        let obj = {
          ...props.formData
        }
        let add = []
        add.push(obj.provinceCode)
        add.push(obj.cityCode)
        let date = []
        date.push(moment(obj.startDate))
        date.push(moment(obj.endDate))
        let arr = [...obj.scheduleVOS]
        if(arr.length){
          for(let i=0;i<arr.length;i++){
            arr[i] = {...arr[i],scheduleDate:moment(arr[i].scheduleDate)}
          }
        }
       
        form.setFieldsValue({
          activityName:obj.activityName,
          address:add,
          activityDate:date,
          activitySite:obj.activitySite,
          activityOrganizers:obj.activityOrganizers,
          activityContent:obj.activityContent,
          pictureKey:{imgKey:obj.pictureKey,imgUrl:obj.pictureUrl},
          thumbnailPictureKey:{imgKey:obj.thumbnailPictureKey,imgUrl:obj.thumbnailPictureUrl},
          scheduleVOS:arr.length?arr:[]
        })
      }
    },[props.formData])
    useEffect(()=>{
      let obj = {
        ...props.formData
      }
      if(options.length == 0){
        return 
      } else if(addressIsReady){
        let filter= options.filter((t:any)=>t.addressCode === obj.provinceCode)
        if(filter.length){
          onChange(obj.provinceCode,filter)
        }
       
      }
      
    },[options])
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    }
    function pictureList(obj:object){
       form.setFieldsValue({'pictureKey':obj})
    }
    function thumbnailPictureList(obj:object){
      form.setFieldsValue({'thumbnailPictureKey':obj})
    }
    const normFile = (e: any) => {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    };
    function searchFirstAddress(){
      post(url,{addressLevel: 1  }).then(res =>{
          let arr:any = []
          for(let item in res){
              let obj = {
                  ...res[item],
                  value:res[item].addressCode,
                  label:res[item].addressName,
                  isLeaf: false
              }
              arr.push(obj)
          }
          setOptions(arr)
      })
      
      setAddressIsReady(true)
  }
  function searchSecondAdd(selectedOptions:any){
      let obj = {
          addressLevel:2,
          parentId:selectedOptions[0].addressCode
      }
     
      post(url,{...obj}).then(res =>{
          const targetOption = {
              ...selectedOptions[0],
              children:[],
              loading:true
          }
          for(let item in res){
              let obj = {
                  ...res[item],
                  value:res[item].addressCode,
                  label:res[item].addressName
              }
              targetOption.children.push(obj)
          }
          let arr:any = [...options]
          for(let item in arr){
              if(arr[item].id == targetOption.id){
                  arr[item] = {
                      ...targetOption
                  }
              }
          }
          targetOption.loading = false
          setOptions(arr)
          setAddressIsReady(false)
      })
  }
  function onChange(value:any, selectedOptions:any){
    searchSecondAdd(selectedOptions)
      return value
    };
    return (
      <div>
        <Form
          form={form}
          name="validate_other"
          layout="inline"
          {...formItemLayout}
          initialValues={
            {
              activitySite:'',
              activityOrganizers:'',
              activityContent:'',
              initialValues:cityList.length > 0?cityList : []
            }
          }
        >
          <Form.Item 
              name="activityName"
              label="活动名称"
              style={{width:'40%'}}
              rules={[{ required: true }]}
              >
            <Input />
          </Form.Item>
          <Form.Item 
            name="address"
            style={{width:'40%'}}
            rules={[{ required: true }]}
            label="活动地址">
              <Cascader
                options={options}
                loadData={searchSecondAdd}
                onChange={onChange} 
                changeOnSelect 
            />
          </Form.Item>
          <Form.Item 
          name="activityDate"
          style={{width:'100%',margin:'15px 0'}}
          rules={[{ required: true }]}
          label="活动时间">
            <RangePicker/>
          </Form.Item>
          <Form.Item 
              name="activitySite"
              label="活动地点"
              style={{width:'40%'}}
              >
            <Input />
          </Form.Item>
          <Form.Item 
              name="activityOrganizers"
              label="活动主办方"
              style={{width:'40%'}}
              >
            <Input />
          </Form.Item>
          <Form.Item 
              name="activityContent"
              label="活动内容"
              style={{width:'100%',margin:'15px 0'}}
              >
            <Input.TextArea />
          </Form.Item>
          <Form.Item 
              name="pictureKey"
              label="活动图"
              style={{width:'40%'}}
              rules={[{ required: true }]}
              valuePropName="fileList"
              getValueFromEvent={normFile}
              >
            <Upload 
              recommendSize={'推荐尺寸：1035*261'}
              pictureKey={pictureList}
              >
            </Upload>
          </Form.Item>
          <Form.Item 
              name="thumbnailPictureKey"
              label="缩略图"
              style={{width:'40%'}}
              rules={[{ required: true }]}
              valuePropName="fileList"
              getValueFromEvent={normFile}
              >
            <Upload 
              recommendSize={'用于分享时展示'}
              pictureKey={thumbnailPictureList}
              >
            </Upload>
          </Form.Item>
          
          <Form.Item 
              label="日程"
              style={{width:'100%'}}
              name="scheduleVOS"
              >
            <Form.List name="scheduleVOS">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        {...restField}
                        name={[name, 'scheduleName']}
                        rules={[{ required: true, message: '请输入日程名称' }]}
                      >
                        <Input placeholder="请输入日程名称" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'scheduleDate']}
                        rules={[{ required: true, message: '请选择日期' }]}
                      >
                        <DatePicker placeholder='请选择日期'/>
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      添加
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form.Item>
          <Form.Item  style={{width:'100%',margin:'15px'}}>
            <Button type="primary" onClick={sumbit}>
              下一步
            </Button>
            <Button htmlType="submit">
              预览
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  };
  








  